<!--
  * 门店
  *
  * @Author:    -
  * @Date:      2025-03-21 08:31:36
  * @Copyright  -
-->
<template>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
            <a-form-item label="平台" class="smart-query-form-item">
                <SmartEnumRadio width="200px" v-model:value="queryForm.tp" enumName="SHOP_TP_ENUM" :isButton="true" placeholder="平台" @change="onSearch"/>
            </a-form-item>
            <a-form-item label="授权状态" class="smart-query-form-item">
                <SmartEnumRadio width="200px" v-model:value="queryForm.authStatus" enumName="SHOP_AUTH_STATUS_ENUM" :isButton="true" placeholder="授权状态" @change="onSearch"/>
            </a-form-item>
            <a-form-item label="门店" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.shopKey" placeholder="门店" @keyup.enter.native="onSearch"/>
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="onSearch">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <!-- <a-button @click="showForm" type="primary" size="small">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button> -->
                <a-button @click="addShop('mtcy')" type="primary" size="small">
                    <template #icon>
                        <PlusCircleFilled />
                    </template>
                    美团餐饮
                </a-button>
                <!-- <a-button @click="addShop('mtsg')" type="primary" size="small">
                    <template #icon>
                        <PlusCircleFilled />
                    </template>
                    美团闪购
                </a-button>
                <a-button @click="addShop('mtyy')" type="primary" size="small">
                    <template #icon>
                        <PlusCircleFilled />
                    </template>
                    美团医药
                </a-button> -->
                <a-button @click="addShop('elemecy')" type="primary" size="small">
                    <template #icon>
                        <PlusCircleFilled />
                    </template>
                    饿了么餐饮
                </a-button>
                <!-- <a-button @click="addShop('ebls')" type="primary" size="small">
                    <template #icon>
                        <PlusCircleFilled />
                    </template>
                    饿百零售
                </a-button> -->
                <a-button @click="addShop('jdcy')" type="primary" size="small">
                    <template #icon>
                        <PlusCircleFilled />
                    </template>
                    京东餐饮
                </a-button>
                <!-- <a-button @click="addShop('jdls')" type="primary" size="small">
                    <template #icon>
                        <PlusCircleFilled />
                    </template>
                    京东零售
                </a-button>
                <a-button @click="addShop('ddls')" type="primary" size="small">
                    <template #icon>
                        <PlusCircleFilled />
                    </template>
                    抖店零售
                </a-button> -->
                <a-button @click="confirmBatchDelete" type="primary" danger size="small" :disabled="selectedRowKeyList.length == 0">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table
            size="small"
            :dataSource="tableData"
            :columns="columns"
            rowKey="id"
            bordered
            :loading="tableLoading"
            :pagination="false"
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
            <template #bodyCell="{ column, record, text  }">
                <template v-if="column.dataIndex === 'tp'">
                    <a-tag v-if="text==='mtcy'" color="orange">美团餐饮</a-tag>
                    <a-tag v-if="text==='mtsg'" color="orange">美团闪购</a-tag>
                    <a-tag v-if="text==='mtyy'" color="orange">美团医药</a-tag>
                    <a-tag v-else-if="text==='elemecy'" color="blue">饿了么餐饮</a-tag>
                    <a-tag v-else-if="text==='ebls'" color="blue">饿百零售</a-tag>
                    <a-tag v-else-if="text==='jdcy'" color="green">京东餐饮</a-tag>
                    <a-tag v-else-if="text==='jdls'" color="green">京东零售</a-tag>
                    <a-tag v-else-if="text==='ddls'" color="green">抖店零售</a-tag>
                </template>
                <template v-if="column.dataIndex === 'shopId'">
                    <a-typography-paragraph :copyable="{ text: record.shopId }">门店ID：{{ record.shopId }}</a-typography-paragraph>
                    门店名称：<a-button @click="openShop(record)" type="link"><a-typography-text underline type="success">{{ record.shopName }}</a-typography-text></a-button>
                </template>
                <template v-if="column.dataIndex === 'authStatus'">
                    <a-tag :color="text===-1 ? 'error' : 'processing'">{{ $smartEnumPlugin.getDescByValue('SHOP_AUTH_STATUS_ENUM', text) }}</a-tag>
                    <a-button v-if="text===-1" @click="addShop(record.tp)" type="link"><a-typography-text underline type="success">重新授权</a-typography-text></a-button>
                    <p style="margin-top: 10px;">授权时间：{{ record.authTime }}</p>
                   
                </template>
                <template v-if="column.dataIndex === 'shopLogo'">
                    <a-image :width="80" :src="text" />
                </template>
                <template v-if="column.dataIndex === 'remark'">
                    <a-tooltip>
                        <template #title>{{text}}</template>
                        <span class="text-wrap">{{text}}</span>
                    </a-tooltip>
                </template>
                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button @click="showForm(record)" type="link">编辑</a-button>
                        <a-button @click="onDelete(record)" danger type="link">删除</a-button>
                        <a-button type="primary" v-if="record.tp!=='jdcy'" @click="goCopy(record)">》》复制到京东</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination
                showSizeChanger
                showQuickJumper
                show-less-items
                :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize"
                v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize"
                :total="total"
                @change="queryData"
                @showSizeChange="queryData"
                :show-total="(total) => `共${total}条`"
            />
        </div>

        <ShopForm  ref="formRef" @reloadList="queryData"/>

    </a-card>
</template>
<script setup>
    import { reactive, ref, onMounted } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { shopApi } from '/@/api/crawler/shop/shop-api';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import ShopForm from './shop-form.vue';
    import SmartEnumRadio from '/@/components/framework/smart-enum-radio/index.vue';
    import { useRouter } from 'vue-router';
    //import FilePreview from '/@/components/support/file-preview/index.vue'; // 图片预览组件
    // ---------------------------- 表格列 ----------------------------
    const columns = ref([
        {
            title: '平台',
            dataIndex: 'tp',
            ellipsis: true,
            width:50
        },
        {
            title: '门店',
            dataIndex: 'shopId',
            ellipsis: true,
            width:180
        },
        {
            title: '门店头像',
            dataIndex: 'shopLogo',
            ellipsis: true,
            width:80,
            align:'center'
        },
        {
            title: '营业状态',
            dataIndex: 'shopStatus',
            ellipsis: true,
            width:80,
            align: 'center'
        },
        {
            title: '授权状态',
            dataIndex: 'authStatus',
            ellipsis: true,
            width:110,
            align: 'center'
        },
        {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
            width:80
        },
        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: 60,
        },
    ]);

    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
        shopKey: undefined, //门店
        authStatus: undefined, //授权状态
        tp:undefined,
        pageNum: 1,
        pageSize: 10,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);

    // 重置查询条件
    function resetQuery() {
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }

    // 搜索
    function onSearch(){
      queryForm.pageNum = 1;
      queryData();
    }

    // 查询数据
    async function queryData() {
        tableLoading.value = true;
        try {
            let queryResult = await shopApi.queryPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }


    onMounted(queryData);

    // ---------------------------- 添加/修改 ----------------------------
    const formRef = ref();

    function showForm(data) {
        formRef.value.show(data);
    }

    // ---------------------------- 单个删除 ----------------------------
    //确认删除
    function onDelete(data){
        Modal.confirm({
            title: '提示',
            content: '确定要删除选吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestDelete(data);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求删除
    async function requestDelete(data){
        SmartLoading.show();
        try {
            let deleteForm = {
                goodsIdList: selectedRowKeyList.value,
            };
            await shopApi.delete(data.id);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    const selectedRowKeyList = ref([]);

    function onSelectChange(selectedRowKeys) {
        selectedRowKeyList.value = selectedRowKeys;
    }

    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await shopApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    async function addShop(type) {
        let randomNum = Math.floor(100000 + Math.random() * (999999 - 100000))
        let data={tp:type,uuid:'UTS_'+randomNum.toString()}
        let channel=''
        if(type === 'ebls'){
            channel='ebShop'
            data.url='https://nr.ele.me/'
        }else if(type === 'mtsg' || type === 'mtcy'|| type === 'mtyy'){
            channel='mtShop'
            data.url='https://e.waimai.meituan.com/new_fe/login_gw#/login'
        }else if(type === 'elemecy'){
            channel='elemecyShop'
            data.url='https://melody.shop.ele.me/app/'
        }else if(type === 'jdcy' || type === 'jdls'){
            channel='jdcyShop'
            data.url='https://store.jddj.com/'
        }else if(type === 'dddj'){
            channel='dddjShop'
            data.url='https://fxg.jinritemai.com/login/common?next=https%3A%2F%2Fjsls.jinritemai.com%2F'
        }
        
        window.electron.invoke(channel,data).then(async (respon)=>{
            console.log('addShop respon',respon)
            await shopApi.add(respon);
            message.success('授权成功,请关闭窗口！');
            queryData();
        })
    }

    async function openShop(row) {
        //let row = await shopApi.info(id).data;
        let data={tp:row.tp,shopId:row.shopId,cookie:row.cookiestr}
        let channel='openShop'
        let type=row.tp
        if(type === 'ebls'){
            data.url='https://nr.ele.me'
            data.domain='.ele.me'
        }else if(type === 'mtcy'|| type === 'mtyy'){
            data.url='https://e.waimai.meituan.com'
            data.domain='.meituan.com'
        }else if(type === 'mtsg'){
            data.url='https://shangoue.meituan.com'
            data.domain='.meituan.com'
        }else if(type === 'elemecy'){
            data.url='https://melody.shop.ele.me'
            data.domain='.ele.me'
        }else if(type === 'jdcy' || type === 'jdls'){
            data.url='https://store.jddj.com'
            data.domain='.jddj.com'
        }else if(type === 'dddj'){
            data.url='https://jsls.jinritemai.com'
            data.domain='.jinritemai.com'
        }
        console.log(channel,data)
        window.electron.send(channel,data)
    }
    //去复制
    const router = useRouter()

    function goCopy(row){
        router.push({
            path:'/shopcopy',
            query:{shopId:row.shopId,shopName:row.shopName,showName:row.shopName+'('+row.shopId+')',cookiestr:row.cookiestr,tp:row.tp,id:row.id},
            meta:{title:'C_'+row.shopName}
        })
    }
</script>
<style scoped lang="less">
  .text-wrap {
    white-space: normal; // 允许文本换行
    word-break: break-word; // 在长单词或URL地址内部进行换行
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 限制显示的行数为3行 */
  }
</style>
